package linkedlist.pro;

import linkedlist.ListNode;

/**
 * @Classname : RemoveNthNodeFromEndOfList
 * @Description :
 * <a href="https://leetcode.cn/problems/remove-nth-node-from-end-of-list/">19. 删除链表的倒数第 N 个结点</a>
 * @Author : chentianyu
 * @Date 2022/12/27 22:14
 */


public class RemoveNthNodeFromEndOfList {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(0, head);
        ListNode slow = dummy, fast = head;
        // 快指针先走n步，由于慢指针初始在负一步，快指针相当于先于慢指针n+1步
        // 这与最终想要停留的位置是一致的，慢指针停于目标删除节点的前一个，快指针停于null，相差了n+1步
        for (int i = 0; i < n; i++) {
            fast = fast.next;
        }
        while (fast != null) {
            fast = fast.next;
            slow = slow.next;
        }
        slow.next = slow.next.next;
        return dummy.next;
    }
}
